package com.laoyao.controller;

import com.aliyuncs.exceptions.ClientException;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.laoyao.comm.config.CrossOrigin;
import com.laoyao.comm.model.Code;
import com.laoyao.comm.model.Fans;
import com.laoyao.comm.model.User;
import com.laoyao.service.SmsDemo;
import com.laoyao.service.UserService;
import com.laoyao.util.DateUtil;
import com.laoyao.util.GUIDKeyGen;
import com.laoyao.util.MD5Util;
import com.laoyao.util.TextUtil;
import com.laoyao.util.UIDUtil;
import com.laoyao.util.abc;
import com.laoyao.validate.UserValidate;

@CrossOrigin
public class UserController extends Controller {
	private static UserService dao = new UserService();
	//注册
	public void register(){
		User user = getBean(User.class,"");
		String pwd2 =  getPara("pwd2");
		String token = getPara("token");
		String code = getPara("code");
		User existUser =  dao.findUserByAccount(user.getAccount());
		User existTel = dao.findUserByTel(user.getTel());
		
		if(TextUtil.isEmpty(user.getAccount())||user.getAccount().trim().length()<3){
			setAttr("msg","账号不能小于三个字符");
			renderJson();
			return;
		}
		if(user.getAccount().matches("\\W+")){
			setAttr("msg","账号只能是数字或者字母");
			renderJson();
			return;
		}
		if(user.getAccount().length()>12){
			setAttr("msg","账号不能大于于12个字符");
			renderJson();
			return;
		}
		
		if(existUser!=null){
			setAttr("msg","用户账号已存在！");
			renderJson();
			return;
		}
		if(existTel!=null){
			setAttr("msg","手机号已存在！");
			renderJson();
			return;
		}
		if(TextUtil.isEmpty(user.getPwd())||!user.getPwd().equals(pwd2)){
			setAttr("msg","密码不能为空且两次密码要一致！");
			renderJson();
			return;
		}
		if(user.getPwd().length()<6||user.getPwd().length()>20){
			setAttr("msg","密码长度不能小于6位！且不能大于20位");
			renderJson();
			return;
		}
		if(!dao.checkCode(token, code)){
			setAttr("msg","验证码无效！");
			renderJson();
			return;
		}
		
		user.setPwd(MD5Util.GetMD5Code(user.getPwd()));
		user.setUserName("网友_"+GUIDKeyGen.getGUIDKey().substring(0, 10));
		renderJson("success",user.save());
	}
	//用户登录
	public void login(){
		String account = getPara("account");
		String pwd = getPara("pwd");
		User user = dao.userLogin(account, com.laoyao.util.MD5Util.GetMD5Code(pwd));
		renderJson("userData",user);
	}
	
	//获取用户信息
	public void getUserById(){
		String id = getPara("id");
		String uid = getPara("uid");
		//获取用户信息
		String sql = "select id,account,userName,photo,sex,birthday,state,level,currentExp,upgradeExp,signature,registerTime,changeNameNum,role,vipTime "
				+ "from v_user where id=?";
		setAttr("userData",Db.findFirst(sql, id));
		//获取关注和被关注数
		sql = "select count(*) num from v_fans where uid=?";
		setAttr("mylike",Db.findFirst(sql,id).get("num"));
		sql = "select count(*) num from v_fans where rid=?";
		setAttr("myfans",Db.findFirst(sql,id).get("num"));
		setAttr("isFans",dao.isFans(uid, id));//判断是否关注
		//获取投稿数量
		sql = "select count(*) num from v_video where userId=?";
		setAttr("mytg",Db.findFirst(sql,id).get("num"));
		
		renderJson();
	}
	
	//关注
	public void fansUser(){
		Fans f = getBean(Fans.class,"");
		Integer flag = getParaToInt("flag");
		
		if(flag==0){
			renderJson("success",f.delete());
		}
		
		if(flag==1){
			try {
				renderJson("success",f.save());
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		
	}
	//单独获取粉丝数量
	public void getFansNum(){
		String id = getPara("id");
		renderJson("myfans",dao.getFansNum(id));
	}
	//修改用户信息
	@Before(UserValidate.class)
	public void update(){
		User u = getBean(User.class,"");
		u.remove("userName");
		u.remove("changeNameNum");
		setAttr("success",u.update());
		setAttr("user",dao.findUserById(u.getId()));
		renderJson();
	}
	//修改用户名称
	public void changeName(){
		Integer id = getParaToInt("id");
		String name = getPara("userName");
		if(TextUtil.isEmpty(name)||name.length()<3||name.length()>12){
			renderJson("msg","用户名不能为空，且长度在3-12字符之间");
			return;
		}
		String sql="select changeNameNum from v_user where id=?";
		Integer num = Db.findFirst(sql,id).getInt("changeNameNum");
		if(num<=0){
			renderJson("msg","您的更名次数用完了");
			return;
		}
		
		//改名
		sql = "update v_user set changeNameNum=changeNameNum-1,userName=? where id=?";
		setAttr("success",Db.update(sql,name,id));
		setAttr("user",dao.findUserById(id));
		renderJson();
	}
	//修改密码
	public void changePwd(){
		String account = getPara("account");
		String pwd = getPara("pwd");
		String pwd1 = getPara("pwd1");
		String pwd2 = getPara("pwd2");
		
		if(dao.userLogin(account, MD5Util.GetMD5Code(pwd))==null){
			setAttr("msg","原始密码不正确！");
			setAttr("errorPwd",true);
			renderJson();
			return;
		}
		
		if(TextUtil.isEmpty(pwd1)||!pwd1.equals(pwd2)){
			setAttr("msg","密码不能为空且两次密码要一致！");
			renderJson();
			return;
		}
		if(pwd1.length()<6||pwd1.length()>20){
			setAttr("msg","密码长度不能小于6位！且不能大于20位");
			renderJson();
			return;
		}
		String sql = "update  v_user set pwd=? where account=?";
		renderJson("success",Db.update(sql,MD5Util.GetMD5Code(pwd1),account));
	}
	
	//获取验证码
	public void getCode() throws ClientException{
		String tel = getPara("tel");
		String code = abc.generateRandCode(4);
		String token = UIDUtil.getUUID();
		SmsDemo.sendSms(tel, code);
		Code c = new Code();
		c.setCode(code);
		c.setOutTime(DateUtil.addTime(300));//设置过期时间5分钟
		c.setToken(token);
		c.save();
		renderJson("token",token);
	}
	
	public void resetPwd(){
		String tel = getPara("tel");
		String token = getPara("token");
		String code = getPara("code");
		if(dao.checkCode(token, code)){
			String newPwd = abc.generateRandCode(6);
			Record r = new Record();
			r.set("tel", tel);
			r.set("pwd", MD5Util.GetMD5Code(newPwd));
			Db.update("v_user", "tel", r);
			renderJson("newPwd",newPwd);
		}else{
			renderJson("msg","验证码无效");
		}
		
	}
	/*public void resetPwd(){
		String tel = getPara("tel");
		String pwd1 = getPara("pwd1");
		String pwd2 = getPara("pwd2");
		
		if(TextUtil.isEmpty(pwd1)||!pwd1.equals(pwd2)){
			setAttr("msg","密码不能为空且两次密码要一致！");
			renderJson();
			return;
		}
		if(pwd1.length()<6||pwd1.length()>20){
			setAttr("msg","密码长度不能小于6位！且不能大于20位");
			renderJson();
			return;
		}
		Record r = new Record();
		r.set("tel", tel);
		r.set("pwd", MD5Util.GetMD5Code(pwd1));
		renderJson("success",Db.update("v_user", "tel", r));
		
	}*/
	
	
}
